import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import account from '@/store/modules/account';
import app from '@/store/modules/app';
import routes from '@/store/modules/routes';
import settings from '@/store/modules/settings';
import socket from '@/store/modules/socket';
import views from '@/store/modules/views';

Vue.use(Vuex);

const persistedStatePlugin = createPersistedState({
	key: 'boot',
	storage: window.localStorage,
	paths: ['account', 'app', 'routes', 'settings'],
	rehydrated(store) {
		/**
		 * @description 解决刷新页面后路由定位到 AsyncRoutes 的问题，
		 * 因为在 router/mutation.js 中， 以 routeTime 和 AccountInfo time 是否相同来判断加入路由，
		 * 所以在刷新页面后初始化 Vuex 时将 routeTime 重置
		 * @date 2020/4/19 16:39
		 **/
		store.state.routes.time = null;
	}
});

// https://webpack.js.org/guides/dependency-management/#requirecontext
// const modulesFiles = require.context('./modules', true, /\.js$/);

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
// const modules = modulesFiles.keys().reduce((modules, modulePath) => {
// 	// set './app.js' => 'app'
// 	const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1');
// 	const value = modulesFiles(modulePath);
// 	modules[moduleName] = value.default;
// 	return modules;
// }, {});

const store = new Vuex.Store({
	modules: {
		account,
		app,
		routes,
		settings,
		socket,
		views
	},
	getters: {
		token: state => state.account.token,
		info: state => state.account.info,
		sidebar: state => state.app.sidebar,
		size: state => state.app.size,
		device: state => state.app.device,
		routes: state => state.routes.allRoutes,
		routeTime: state => state.routes.time,
		title: state => state.settings.title,
		socketClient: state => state.socket.client,
		subscriptions: state => state.socket.subscriptions,
		visitedViews: state => state.views.visitedViews,
		cachedViews: state => state.views.cachedViews
	},
	// plugins:
	// 	process.env.NODE_ENV !== 'production'
	// 		? [createLogger(), persistedStatePlugin]
	// 		: [persistedStatePlugin]
	plugins: [persistedStatePlugin]
});

export default store;
